package com.mall.malllibrary.global

import android.os.Handler
import android.os.Looper
import com.mall.malllibrary.util.storage.MemoryStorage

/*
* 全局控制配置类
* */
// private constructor()用户控制配置类对象不可被实例化
 class Configurator private constructor(){

     private object Holder{
         internal val INSTANCE = Configurator()
     }

    // 内部静态属性，类型直接访问
    companion object{
        // 这里获取到全局的存储容器
        private val mStore : MemoryStorage = MemoryStorage.instance
        // Handler需要反复使用不放提前创建
        private val mHandler = Handler()

        internal val instance : Configurator
            get() = Holder.INSTANCE
    }

    // 初始化方法
    init {

        // 加一个标签，判断配置是否完成,现在还没开始配置
        mStore.addData(GlobalKeys.IS_CONFIGURE_READY, false)
        mStore.addData(GlobalKeys.HANDLER, mHandler)
    }
    // 访问服务api设置
    fun withApiHost(host: String):Configurator{
        mStore.addData(GlobalKeys.HOST, host)
        return this
    }

    fun withLoaderDelayed(delayed:Long):Configurator{
        mStore.addData(GlobalKeys.LOADER_DELAYED, delayed)
        return this
    }
    // 结束配置
    fun configure(){
        mStore.addData(GlobalKeys.IS_CONFIGURE_READY, true)
        // 配置完成做一些回收动作
    }

    fun<T> getConfigureation(key:String):T{
        return mStore.getData(key)
    }

    fun<T> getConfigureation(key:Enum<*>):T{
        return getConfigureation(key.name)
    }

    fun checkConfiguration(){
        val isReady: Boolean = mStore.getData(GlobalKeys.IS_CONFIGURE_READY)
        if (!isReady){
            throw RuntimeException("configuration is not ready")
        }
    }

}